package com.lancoo.answer.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * paper层级的viewpager2专用
 */
public class ViewPagerContainer extends FrameLayout {

    private static final String TAG = "ViewPagerContainer";
    private int currentIndex;

    public ViewPagerContainer(@NonNull Context context) {
        super(context);
    }

    public ViewPagerContainer(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public ViewPagerContainer(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    int lastX;
    int lastY;
    private int scrollState;
    private boolean isRightScroll=false;


    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        int x = (int) event.getRawX();
        int y = (int) event.getRawY();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // 记录触摸点坐标
                lastX = x;
                lastY = y;
                scrollState=0;
                isRightScroll=false;
                break;
            case MotionEvent.ACTION_MOVE:
                // 计算偏移量
                int offsetX = x - lastX;
                int offsetY = y - lastY;
                if(scrollState==0){
                    scrollState= offsetX>0?1:2;
                }
                if(offsetX>0){
                    isRightScroll=true;
                }
                if(!isRightScroll){
                    // 在当前left、top、right、bottom的基础上加上偏移量
                    boolean isHorizontal = Math.abs(offsetX) > Math.abs(offsetY);
                    Log.e("dispatch move","offsetX:"+offsetX);
                    //重新设置初始化坐标
                    lastX = x;
                    lastY = y;
                    if (offsetX < 0 && isHorizontal&&Math.abs(offsetX)>20){
                        if (listener!=null){
                            listener.onScrolled();
                        }
                    }
                }
                break;
            case MotionEvent.ACTION_CANCEL:
                break;
        }
        return super.dispatchTouchEvent(event);
    }

    private ScrollListener listener;

    public void setListener(ScrollListener listener) {
        this.listener = listener;
    }


    public void setCurrentIndex(int currentIndex) {
        this.currentIndex = currentIndex;
    }


    public interface ScrollListener{
        void onScrolled();
    }
}
